<?php

namespace App\Repositories;
use App\Interfaces\DiscountService;
use App\Interfaces\OrderService;
use App\Models\Discount;
use App\Models\DiscountType;
use App\Models\DiscountLimitAmount;
use App\Models\Goods;
use App\Exceptions\Interfaces\DiscountServiceException;
use Illuminate\Database\Eloquent\Collection;
use Auth,Log;

class DiscountRepository implements DiscountService
{

    /**
     * 根据商品获取当前可用的限时折扣
     * @param int $goods_id      商品id
     * @param int $user_id       用户id
     * @return mixed
     */
    /*public function getCanUseDiscountByGoodsId($goods_id, $user_id = ''){

        $current_time = date('Y-m-d H:i:s');

        if (empty($goods_id)) {

            throw new DiscountServiceException("用户id不能为空");
        }

        //第一步：获取商品信息
        $goods = Goods::find($goods_id);


        //第二步：根据商品id、商品所属分类、店铺、品牌查询对应的以及全场通用的限时折扣
        $query = Discount::groupBy('discount_id')->orderBy('discount.updated_at', 'desc')

        				->leftJoin('discount_type', 'discount.discount_id', '=', 'discount_type.discount_id')

           			->whereRaw('discount.start_time <= now() and discount.end_time > now()');

        if ($user_id){

          $query = $query->leftJoin('discount_limit_amount', 'discount.discount_id', '=', 'discount_limit_amount.discount_id');

          $query = $query->select('discount.*', 'discount_type.discount_type_id', 'discount_type.use_id');

          $query = $query->whereRaw("discount.discount_type = 1 and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now() and discount.limit_amount >= ifnull((select amount from discount_limit_amount where discount_limit_amount.user_id = $user_id and discount_limit_amount.discount_id = discount.discount_id),0)");

          $query = $query->orWhereRaw("discount.discount_type = 2 and discount_type.use_id = $goods_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now() and discount.limit_amount >= ifnull((select amount from discount_limit_amount where discount_limit_amount.user_id = $user_id and discount_limit_amount.discount_id = discount.discount_id),0)");

          if ($goods->cat_id) {

            $query = $query->orWhereRaw("discount.discount_type = 3 and discount_type.use_id = $goods->cat_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now() and discount.limit_amount >= ifnull((select amount from discount_limit_amount where discount_limit_amount.user_id = $user_id and discount_limit_amount.discount_id = discount.discount_id),0)");
          }//end if()

          if ($goods->shop_id) {

            $query = $query->orWhereRaw("discount.discount_type = 4 and discount_type.use_id = $goods->shop_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now() and discount.limit_amount >= ifnull((select amount from discount_limit_amount where discount_limit_amount.user_id = $user_id and discount_limit_amount.discount_id = discount.discount_id),0)");
          }//end if()

          if ($goods->brand_id) {

            $query = $query->orWhereRaw("discount.discount_type = 5 and discount_type.use_id = $goods->brand_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now() and discount.limit_amount >= ifnull((select amount from discount_limit_amount where discount_limit_amount.user_id = $user_id and discount_limit_amount.discount_id = discount.discount_id),0)");
          }//end if()
        }else{

          $query = $query->select('discount.*', 'discount_type.discount_type_id', 'discount_type.use_id');


          $query = $query->whereRaw("discount.discount_type = 1 and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()");

          $query = $query->orWhereRaw("discount.discount_type = 2 and discount_type.use_id = $goods_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()");

          if ($goods->cat_id) {

            $query = $query->orWhereRaw("discount.discount_type = 3 and discount_type.use_id = $goods->cat_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()");
          }//end if()

          if ($goods->shop_id) {

            $query = $query->orWhereRaw("discount.discount_type = 4 and discount_type.use_id = $goods->shop_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()");
          }//end if()

          if ($goods->brand_id) {

            $query = $query->orWhereRaw("discount.discount_type = 5 and discount_type.use_id = $goods->brand_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()");
          }//end if()
        }

// dd($query->get()->toArray());
    	//第三步：返回可用的限时折扣信息
    	return $query->get();

    }*/



    /**
     * 根据商品id获取商品可用的最大的限时折扣
     * @param int $goods_id      商品id
     * @param int $user_id       用户id
     * @return mixed
     */
    public function getCanUseBiggestDiscountByGoodsId($goods_id){

      $goods = Goods::find($goods_id);

      if ($goods) {

        /*select
        `discount`.*
        from `discount`
        where `discount_value` = (
        select
        MAX(`discount`.`discount_value`)
        from `discount`
        left join `discount_type` on `discount`.`discount_id` = `discount_type`.`discount_id`
        where
        `discount`.`deleted_at` is null
        and discount.discount_type=1
        or discount.discount_type=2 and discount_type.use_id = 967 and discount.deleted_at is null
        or discount.discount_type=3 and discount_type.use_id = 394 and discount.deleted_at is null
        or discount.discount_type=4 and discount_type.use_id = 5 and discount.deleted_at is null
        or discount.discount_type=5 and discount_type.use_id = 99 and discount.deleted_at is null
        order by `discount`.`discount_value` desc
        )*/

        $query = Discount::whereRaw("
                  discount_value = (
                      select MIN(`discount`.`discount_value`)
                      from `discount`
                      left join `discount_type` on `discount`.`discount_id` = `discount_type`.`discount_id`
                      where
                      `discount`.`deleted_at` is null
                      and discount.discount_type=1 and discount.start_time <= now() and discount.end_time > now()
                      or discount.discount_type=2 and discount_type.use_id = $goods_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()
                      or discount.discount_type=3 and discount_type.use_id = $goods->cat_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()
                      or discount.discount_type=4 and discount_type.use_id = $goods->shop_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()
                      or discount.discount_type=5 and discount_type.use_id = $goods->brand_id and discount.deleted_at is null and discount.start_time <= now() and discount.end_time > now()
                      order by `discount`.`discount_value` desc
                    )
                  ");

        // dd($query->toSql());

        // dd($query->first()->toArray());

        return $query->first();
      }
    }


    /**
     * 根据要购买的商品数组获取用户购买这些商品时可用的限时折扣
     * @param int $user_id      						用户id
     * @param array $buyGoods      						商品数组
     * @param int $not_available_use_discount_id		除掉的限时折扣id
     * @return mixed  可用的限时折扣
     */
    /*public function getUserCanUseDiscount($user_id, $buyGoods, $not_available_use_discount_id=''){
        $can_use_discount = new Collection();

    	foreach ($buyGoods as $key => $goods) {

    		$single_goods_can_use_discounts = $this->getCanUseDiscountByGoodsId($goods->goods_id, $user_id);

    		foreach ($single_goods_can_use_discounts as $keys => $single_goods_can_use_discount) {

    			foreach ($can_use_discount as $can_use_discount_key => $can_use_discount_value) {

    				if ($single_goods_can_use_discount->discount_id == $can_use_discount_value->discount_id) continue 2;
    			}

    			$can_use_discount = $can_use_discount->add($single_goods_can_use_discount);
    		}

    	}

    	// dd($can_use_discount->toArray());
    	return $can_use_discount;
    }*/

    /**
     * 根据要购买的商品数组获取用户购买这些商品时可用的限时折扣
     * @param int $user_id                             用户id
     * @param array $buyGoods                              商品数组,$buyGoods = ["483" => "2", "503" => "1"];
     * @param int $current_discount_arr        已经选中的要使用的限时折扣以及该折扣要使用的商品数量 current_discount_arr = ['discount_id' => 1, 'goods_number' => 2]
     * @return mixed  可用的限时折扣
     */
    public function getUserCanUseDiscount($user_id, $buyGoods, $current_discount_arr=[]){

        $can_use_discount = new Collection();

       foreach ($buyGoods as $goods_id => $buy_number) {

           $single_goods_can_use_discounts = $this->getCanUseDiscountByGoodsId($goods_id, $user_id);

           foreach ($single_goods_can_use_discounts as $keys => $single_goods_can_use_discount) {

               foreach ($can_use_discount as $can_use_discount_key => $can_use_discount_value) {

                   if ($single_goods_can_use_discount->discount_id == $can_use_discount_value->discount_id) {

                       if ($can_use_discount->count()) {

                           if (!$can_use_discount[$keys]['this_use_goods_number']) {

                               $can_use_discount[$keys]['this_use_goods_number'] = 0;
                           }
                           $can_use_discount[$keys]['this_use_goods_number'] += $buy_number;

                       }
                       continue 2;
                   }
               }

               $can_use_discount = $can_use_discount->add($single_goods_can_use_discount);

               if ($can_use_discount->count()) {

                   if (!$can_use_discount[$keys]['this_use_goods_number']) {

                       $can_use_discount[$keys]['this_use_goods_number'] = 0;
                   }
                   $can_use_discount[$keys]['this_use_goods_number'] += $buy_number;

               }


           }

       }

       foreach ($can_use_discount as $can_use_discount_key => $can_use_discount_value) {

           //获取当前限时折扣可用的商品数量，跟当前要用的数量进行比较，判断是否可用
           $limit_amount = $can_use_discount_value->limit_amount;

           $amount = $can_use_discount_value->amount;;

           if ($current_discount_arr && $current_discount_arr['discount_id']==$can_use_discount_value->discount_id) {

               if(intval($can_use_discount_value->this_use_goods_number + $current_discount_arr['goods_number'])>intval($limit_amount-$amount)){

                   /*if ($can_use_discount_key==0) {

                       $can_use_discount[0]->discount_id='';
                   }else{

                       $can_use_discount = $can_use_discount->forget($can_use_discount_key);
                   }*/

                   // $can_use_discount[$can_use_discount_key]->discount_id='';
                   $can_use_discount[$can_use_discount_key]->discount_id=0;

               }
           }else{

               if(intval($can_use_discount_value->this_use_goods_number)>intval($limit_amount-$amount)){

                   /*if ($can_use_discount_key==0) {

                       $can_use_discount[0]->discount_id='';
                   }else{

                       $can_use_discount = $can_use_discount->forget($can_use_discount_key);
                   }*/

                   // $can_use_discount[$can_use_discount_key]->discount_id='';
                   $can_use_discount[$can_use_discount_key]->discount_id=0;
               }
           }

       }

       return $can_use_discount;
     }

	/**
	 * 根据用户id和限时折扣id获取用户当前已经使用过该折扣的商品数量
     * @param int $user_id      	用户id
     * @param int $discount_id      限时折扣id
     * @return mixed  用户当前已经使用过该折扣的商品数量
	 */
    public function getUsedGoodsAmountByUserIdAndDiscountId($user_id, $discount_id){

    	return DiscountLimitAmount::where('user_id', $user_id)->where('discount_id', $discount_id)->pluck('amount');
    }

	/**
	 * 增加用户限时折扣活动使用的商品数量
	 * @param [int] $user_id  		用户id
	 * @param [int] $discount_id 	限时折扣id
	 * @param [int] $amount   		商品数量
     * @return mixed
	 */
	public function addUserDiscountUseGoodsAmount($user_id, $discount_id, $amount){

       $discount_limit_amount = DiscountLimitAmount::where('user_id', $user_id)->where('discount_id', $discount_id)->first();

       if ($discount_limit_amount) {

           $result = DiscountLimitAmount::where('user_id', $user_id)->where('discount_id', $discount_id)->update(['amount'=>$discount_limit_amount->amount+$amount]);
       }else{

           $result = DiscountLimitAmount::create(['user_id'=>$user_id, 'discount_id'=>$discount_id, 'amount'=>$amount]);
       }

       return $result;
	}

	/**
	 * 根据限时折扣id获取限时折扣信息
	 * @param  int    $discount_id [description]
	 * @return [type]              [description]
	 */
	public function getDiscountInfoByDisncountId($discount_id){
		return Discount::find($discount_id);
	}

	/**
	 * 判断用户的商品是否可以使用指定的限时折扣
	 * @param  [int]  $user_id     [用户id]
	 * @param  [int]  $goods_id    [商品id]
	 * @param  [int]  $discount_id [限时折扣id]
	 * @return boolean              [description]
	 */
	public function isJudgeDiscountCanUse($user_id, $goods_id, $discount_id){
		$discounts = $this->getCanUseDiscountByGoodsId($goods_id, $user_id);
		foreach ($discounts as $key => $value) {
			if ($discount_id == $value->discount_id) {
				return true;
			}
		}
		return false;
	}

}//end class